using System.Collections.Generic;

namespace MimeCloud.Foundations.Collections
{
    
    /// <summary>
    /// Quick and dirty indexed dictionary with fast addition/removal.
    /// TODO - Could get away with just the internal index to key dictionary, by
    /// storing the indexes in the list itself, but would need to
    /// implement enumerators etc
    /// </summary>
    /// <typeparam name="TKey"></typeparam>
    /// <typeparam name="TValue"></typeparam>
    public class IndexedDictionary<TKey, TValue>: Dictionary<TKey, TValue>
    {
        protected IDictionary<int, TKey> _indexDictionary = new Dictionary<int, TKey>();
        protected IDictionary<TKey, int> _keyToIndexDictionary = new Dictionary<TKey, int>();

        public new void Add(TKey key, TValue value)
        {
            base.Add(key, value);
            _keyToIndexDictionary[key] = _indexDictionary.Count;
            _indexDictionary[_indexDictionary.Count] = key;            
        }

        public new TValue this[TKey key]
        {
            get
            {
                return base[key];
            }
            set
            {
                Add(key, value);
            }
        }

        public new bool Remove(TKey key)
        {
            bool result = base.Remove(key);
            int index = _keyToIndexDictionary[key];
            _keyToIndexDictionary.Remove(key);
            _indexDictionary.Remove(index);
            return result;
        }

        public new void Clear()
        {
            _indexDictionary.Clear();
            _keyToIndexDictionary.Clear();
            base.Clear();
        }

        public int IndexOf(TKey key)
        {
            return _keyToIndexDictionary[key];
        }        
        
        public KeyValuePair<int, TValue> ValueAndIndex(TKey key)
        {
            return new KeyValuePair<int, TValue>(IndexOf(key), this[key]);
        }    
    }
}
